package permission

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent/adminrouter"
	"private-domain-overseas-service/tools/ent/predicate"
	"sort"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminRouterTreeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminRouterTreeLogic - 后台菜单树查询接口
func NewAdminRouterTreeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminRouterTreeLogic {
	return &AdminRouterTreeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminRouterTreeLogic) AdminRouterTree() (resp []*types.TreeResponse, err error) {
	adminRouterDAO := permission.NewAdminRouterDao(l.ctx, l.svcCtx)

	// 查询所有菜单
	conditions := make([]predicate.AdminRouter, 0, 1)
	conditions = append(conditions, adminrouter.AdminRouterConstantEQ(bizadmin.NotConstant))
	conditions = append(conditions, adminrouter.AdminRouterStatus(bizadmin.StatusEnabled))
	adminRouters, _, err := adminRouterDAO.AdminRouterConditionsAll(conditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询后台菜单列表失败: %v", err.Error()))
	}

	// 组装数据
	list := convert(adminRouters)

	// 返回递归构造的菜单树
	return buildSimpleMenuTree(list, 0), nil
}

// 构建菜单树
func buildSimpleMenuTree(list []*types.AdminRouterInfo, pid int64) []*types.TreeResponse {
	var result []*types.TreeResponse
	for _, item := range list {
		// 当前的父id等于pid，则添加到结果中
		if item.AdminRouterPid == pid {
			menu := types.TreeResponse{
				Id:    item.ID,
				Label: item.AdminRouterMenuName,
				Order: item.AdminRouterOrder,
				PId:   item.AdminRouterPid,
			}
			// 递归构建子菜单
			menu.Children = buildSimpleMenuTree(list, menu.Id)

			// （二级菜单，三级菜单，四级菜单）都按id升序排序
			sort.Slice(menu.Children, func(i, j int) bool {
				return menu.Children[i].Order < menu.Children[j].Order
			})

			// 添加到这一层级的结果中
			result = append(result, &menu)
		}
	}
	return result
}
